package com.easyOrder.service.impl;

/**
 * Created by liutao on 2017/7/17.
 */

import com.easyOrder.core.utils.HttpClient;
import com.easyOrder.core.utils.UuidUtil;
import com.easyOrder.domain.RongCloudMessage;
import com.easyOrder.domain.RongCloudToken;
import com.easyOrder.service.enums.RongCloudAPI;
import com.easyOrder.service.enums.RongCloudMessageTypes;
import com.easyOrder.service.user.UserService;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;




@Service
@Lazy
public class RongcloudService {

    @Value("${rongcloud.app.key}")
    private String rongCloudAppKey;

    @Value("${rongcloud.app.secret}")
    private String rongCloudAppSecret;

    private Logger logger = Logger.getLogger(UserService.class);

    /**
     * 获取Token
     * @param userId
     * @param name
     * @param portraitUri
     * @return
     */
    public RongCloudToken getToken(String userId, String name, String portraitUri) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("userId", userId);
        params.put("name", name);
        params.put("portraitUri", StringUtils.isBlank(portraitUri) ? "default.jpg" : portraitUri);
        Map<String, String> headers = buildHeaders();
        String response = call(RongCloudAPI.getToken, params, headers);
        RongCloudToken token = new Gson().fromJson(response, RongCloudToken.class);
        return token;
    }

    /**
     * 发送文本消息
     * @param fromUserId
     * @param toUserId
     * @param content
     */
    public String sendTextMessage(String fromUserId, String toUserId, String content, Map<String, String> extra) {
        Map<String, String> headers = buildHeaders();
        Map<String, Object> params = Maps.newHashMap();
        params.put("fromUserId", fromUserId);
        params.put("toUserId", toUserId);
        params.put("objectName", RongCloudMessageTypes.text.getValue());
        RongCloudMessage message = new RongCloudMessage();
        message.setContent(content);
        message.setExtra(extra);
        params.put("content", new Gson().toJson(message, RongCloudMessage.class));
        String response = call(RongCloudAPI.privateMessage, params, headers);
        return response;
    }

    /**
     * build http request headers
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private Map<String, String> buildHeaders() {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("App-Key", rongCloudAppKey);
        String uuid = UuidUtil.newUuidString();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        headers.put("Nonce", uuid);
        headers.put("Timestamp", timeStamp);
        StringBuilder bu = new StringBuilder();
        bu.append(rongCloudAppSecret).append(uuid).append(timeStamp);
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-1");
            digest.update(bu.toString().getBytes("utf8"));
            byte[] digestBytes = digest.digest();
            String digestStr = javax.xml.bind.DatatypeConverter.printHexBinary(digestBytes);
            headers.put("Signature", digestStr);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            logger.error(e, e);
        }
        return headers;
    }

    /**
     * 调用融云API获取返回结果
     * @param api
     * @param params
     * @param headers
     * @return
     */
    private String call(RongCloudAPI api, Map<String, Object> params, Map<String, String> headers) {
        return HttpClient.post(api.getUrl(), params, headers);
    }
}

